package com.hmdp.service.impl;

import ch.qos.logback.core.util.ContextUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.ContentHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private BlogMapper blogMapper;

    @Resource
    private IUserService userService;

    @Autowired
    private IFollowService followService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String BLOG_LIKE = "blog:like:";

    private static final String FEED_KEY = "feed:";

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = blogMapper.selectById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        Long userId = blog.getUserId();
        LambdaQueryWrapper<User> userLambdaQueryWrapper = Wrappers.lambdaQuery();
        userLambdaQueryWrapper.eq(User::getId, userId);
        User user = userService.getOne(userLambdaQueryWrapper);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
        isLike(CollUtil.toList(blog));
        return Result.ok(blog);
    }

    /**
     * 查询博客点赞列表
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        Set<String> top5 = redisTemplate.opsForZSet().range(BLOG_LIKE + id, 0, 4);
        if (top5 == null){
            return Result.ok();
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        if (CollUtil.isEmpty(ids)){
            return Result.ok();
        }
        String idsStr = StrUtil.join(",", ids);

        List<User> list = userService.lambdaQuery()
                .in(User::getId, ids)
                .last("order by field(id," + idsStr + ")")
                .list();
        List<UserDTO> res = list
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(res);
    }

    /**
     * 点赞博客
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        // 1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("用户未登录");
        }
        Long userId = user.getId();
        // 2.判断是否已经点赞
        Double isLike = redisTemplate.opsForZSet().score(BLOG_LIKE + id, userId.toString());
        if (ObjectUtil.isEmpty(isLike)){
            // 没点赞
            // 增加点赞数量
            boolean update = lambdaUpdate().setSql("liked = liked + 1").eq(Blog::getId, id).update();
            // redis中存储该用户的点赞记录
            if (BooleanUtil.isTrue(update)){
                redisTemplate.opsForZSet().add(BLOG_LIKE + id, userId.toString(), System.currentTimeMillis());
            }
        }else{
            // 已点赞
            // 减少点赞数量
            boolean update = lambdaUpdate().setSql("liked = liked - 1").eq(Blog::getId, id).update();
            // redis中删除该用户的点赞记录
            if (BooleanUtil.isTrue(update)){
                redisTemplate.opsForZSet().remove(BLOG_LIKE + id, userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询热门博客
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = lambdaQuery()
                .orderByDesc(Blog::getLiked)
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            User user = userService.getById(userId);
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
        });
        isLike(records);
        return Result.ok(records);
    }

    /**
     * 查询用户关注用户的最新博客
     * @param lastId
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(String lastId, String offset) {
        // 获取当前用户
        UserDTO user = UserHolder.getUser();
        if (ObjectUtil.isEmpty(user)){
            return Result.fail("用户未登录");
        }
        Long userId = user.getId();
        // 查询当前用户的feed流
        // 根据lastId和offset 实现分页查询
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(FEED_KEY + userId, 0, Long.valueOf(lastId), Integer.valueOf(offset), 2);

        if (CollUtil.isEmpty(typedTuples)){
            return Result.ok();
        }
        List<Long> ids = new ArrayList();
        long minTime = 0;
        int off = 1;
        // 获取本次查询的最后一条数据
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            ids.add(Long.valueOf(typedTuple.getValue()));
            long time = typedTuple.getScore().longValue();
            if (time == minTime){
                off++;
            }else{
                minTime = time;
                off = 1;
            }
        }
        List<Blog> blogs = lambdaQuery()
                .in(Blog::getId, ids)
                .last("order by field(id," + StrUtil.join(",", ids) + ")")
                .list();

        isLike(blogs);
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(off);
        return Result.ok(scrollResult);
    }

    /**
     * 发布博文
     * @param blog
     * @return
     */
    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        save(blog);
        // 推送文章到粉丝的关注队列中
        // 查询当前用户的粉丝
        List<Follow> fans = followService.lambdaQuery()
                .eq(Follow::getFollowUserId, user.getId())
                .list();
        // 给每个粉丝的关注队列中加入当前的博客id
        fans.stream().forEach(
                follow -> {
                    String key = FEED_KEY + follow.getUserId();
                    redisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
                }
        );
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 查询是否被点赞
     * @param records
     */
    private void isLike(List<Blog> records) {
        // 1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return;
        }
        Long userId = user.getId();
        records.stream().forEach(
                blog -> {
                    Double score = redisTemplate.opsForZSet().score(BLOG_LIKE + blog.getId(), userId.toString());
                    blog.setIsLike(ObjectUtil.isNotEmpty(score));
                }
        );
    }
}
